package com.arvin.interceptors;

import com.alibaba.fastjson.JSONObject;
import com.arvin.pojo.Result;
import com.arvin.utils.JwtUtil;
import com.arvin.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String url = request.getRequestURI().toString();

        if (url.contains("login") || url.contains("sendMsg") || url.contains("register") || url.contains("reset") || url.contains("swagger-ui") || url.contains("v3")){
            return true;
        }


        //令牌验证
        String token = request.getHeader("token");
        if (token==null|| token.isEmpty()){
            response.setContentType("text/html;charset=utf-8");
            Result result = Result.error("未登录");
            String notlogin = JSONObject.toJSONString(result);
            response.getWriter().write(notlogin);
            return false;
        }
        //验证token
        try {
            Map<String, Object> claims = JwtUtil.parseToken(token);
            //把业务数据存储到ThreadLocal中
            ThreadLocalUtil.set(claims);
            //放行
            return true;
        } catch (Exception e) {
            response.setContentType("text/html;charset=utf-8");
            Result result = Result.error("未登录");
            String notlogin = JSONObject.toJSONString(result);
            response.getWriter().write(notlogin);
            //不放行
            return false;

        }

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清空ThreadLocalUtil中的数据
        ThreadLocalUtil.remove();
    }
}
